package com.lhz.framework.config.converter;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.core.convert.converter.Converter;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * @Author: LiHuaZhi
 * @Date: 2024/1/7 3:27
 * @Description:
 **/
public class TimeStampToLocalDateConverter implements Converter<String, LocalDateTime> {

    @Override
    public LocalDateTime convert(String text) {
        if (StrUtil.isNotEmpty(text)) {
            if (NumberUtils.isCreatable(text)) {
                long timestamp = Long.parseLong(text);
                if (timestamp > 0) {
                    return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
                } else {
                    return null;
                }
            }
            if (text.length() == 10) {
                return DateUtil.parseLocalDateTime(text, "yyyy-MM-dd");
            } else {
                return DateUtil.parseLocalDateTime(text, "yyyy-MM-dd HH:mm:ss");
            }
        }
        return null;
    }
}

